package com.apes.hr.base.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.model.Staffing;
import com.apes.hr.base.model.WorkPost;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.hr.base.repository.StaffingRepository;
import com.apes.hr.recruit.model.ApplyJobOrder;
import com.apes.hr.recruit.model.RecruitOrder;
import com.apes.hr.recruit.repository.ApplyJobOrderRepository;
import com.apes.hr.recruit.repository.RecruitOrderRepository;
import com.apes.hr.transfer.model.QuitJobOrder;
import com.apes.hr.transfer.model.TransferApplicationItem;
import com.apes.hr.transfer.repository.QuitJobOrderRepository;
import com.apes.hr.transfer.repository.TransferApplicationItemRepository;
import com.apes.hr.transfer.repository.TransferApplicationRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Branch;

import com.apes.scm.masterdata.frame.service.BranchService;

import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能：员工编制
 *
 * @author HuJianLin
 * @create 2018-04-28 14:35
 */
@Service("hrStaffingService")
public class StaffingService extends DomainService {
    @Autowired
    public StaffingRepository staffingRepository;
    @Autowired
    public BranchService branchService;
    @Autowired
    public WorkPostService workPostService;

    @Autowired
    public QuitJobOrderRepository quitJobOrderRepository;
    @Autowired
    TransferApplicationItemRepository itemRepository;
    @Autowired
    EmployeeRepository employeeRepository;

    @Autowired
    PartyRoleRepository partyRoleRepository;

    @Autowired
    RecruitOrderRepository recruitOrderRepository;
    @Autowired
    TransferApplicationRepository transferApplicationRepository;

    @Autowired
    TransferApplicationItemRepository ItmRepository;

    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    ApplyJobOrderRepository applyJobOrderRepository;

    public Staffing save(SimpleRequest request) {
        Staffing staffing = request.getO(Staffing.class);
        return create(staffing);
    }

    public Staffing create(Staffing staffing) {
        return staffingRepository.saveAndFlush(staffing);
    }

    public List<Staffing> findAll(SimpleRequest request) {
        return staffingRepository.findAll();
    }

    /**
     * 功能：弹窗或者查询使用  带模糊查找
     *
     */
    public Page<Staffing> findAllPage(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return staffingRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Staffing staffing = staffingRepository.findOne(id);
        if (staffing == null) throw new RuntimeException("人员编码：" + request.get("id") + " 在系统中不存在。");
        staffingRepository.delete(staffing);
        return "删除成功！";
    }

    public Staffing findOne(String id) {
        return staffingRepository.findOne(id);
    }

    public Staffing findByBranchAndWorkPost(SimpleRequest request)  throws RuntimeException{
        String branchId =request.get("branchId");
        Branch branch =  branchService.findOne(branchId);
        String workPostId = request.get("workPostId");
        WorkPost workPost = workPostService.findOne(workPostId);
        List<Staffing> listStaffing =staffingRepository.findByBranchAndWorkPost(branch, workPost);

        if(listStaffing.size()>0){
            return listStaffing.get(0);
        }else {
            return null;
        }
    }

    /**
     * 生成招聘单
     * @param request
     */
    public void recruitOrder (SimpleRequest request){
        List<Staffing> staffings = staffingRepository.findAll();//查询编制
        //查询 待岗 长假 机电技工1
        List<Employee> employeeList = employeeRepository.findOnDutyStateAndPostDescribe();
        //根据部门岗位查询在职人员档案的信息(在职状态为 待岗 长假 机电技工1) 其他数据人员编制里有
        List<RecruitOrder> recruitOrderList = new ArrayList<>();//待生成的招聘单
        staffings.forEach(staffing -> {
            //查询招聘单
            List<RecruitOrder> recruitOrders = recruitOrderRepository.findByStaffingAndState(staffing,"approve");
            List<Employee> empList = new ArrayList<>();//导致缺岗的人
            Set<Employee> employeeSet = new HashSet<>();//写进招聘单的（导致缺岗人）
            Branch branch = staffing.getBranch();
            WorkPost workPost = staffing.getWorkPost();
            //查当前部门岗位 的 待岗 长假 机电技工1 的 list
            List<Employee> employees=employeeList.stream().filter(employee -> employee.getPost()==workPost&&employee.getWorkBranch()==branch).collect(Collectors.toList());
            int realQty = staffing.getRealQty();//正式员工
            int delayQty = staffing.getDelayQty();//待入职
            int transferInQty = staffing.getTransferInQty();//将调入
            int transferOutQty = staffing.getTransferOutQty();//将调出
            int leaveQty = staffing.getLeaveQty();//将离职
            int stopRecruitQty = staffing.getStopRecruitQty();//暂停招聘
            int planQty = staffing.getPlanQty();//定编
            int need_qty = realQty + delayQty + transferInQty - transferOutQty -leaveQty + stopRecruitQty - planQty - employees.size();
            if(need_qty<0 ){
                //生成招聘单
                RecruitOrder recruitOrder = new RecruitOrder();
                recruitOrder.setCompany(partyRoleRepository.findOne("1001"));
                recruitOrder.setBranch(branch);
                recruitOrder.setWorkPost(workPost);
                recruitOrder.setCurrentRecruitQty(-need_qty);
                recruitOrder.setStaffing(staffing);
                recruitOrder.setState("approve");
                Date date = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);//设置起时间
                cal.add(Calendar.MONTH, 1);//增加一个月
                recruitOrder.setEntryDate(cal.getTime());
                recruitOrder.setApproveDate(new Date());
                recruitOrder.setApproveUid(partyRoleRepository.findOne("yyadmin"));
                staffing.setRecruitQty(staffing.getRecruitQty() + recruitOrder.getCurrentRecruitQty());
                staffingRepository.saveAndFlush(staffing);

                //离职导致
                List<QuitJobOrder> quitJobOrderList = quitJobOrderRepository.findByWorkBranchAndPostAndState(branch,workPost,"approve");
                quitJobOrderList.forEach(quitJobOrder -> {empList.add(quitJobOrder.getEmployee());});
                //调动导致
                List<TransferApplicationItem> transferApplicationItemList = ItmRepository.findByBranchAndWorkPostAndIconExecute(branch,workPost,false);
                transferApplicationItemList.forEach(Itm ->{empList.add(Itm.getTransferUid());});
                if( !recruitOrders.isEmpty()){ //缺岗、有招聘单
                    //导致缺岗人 不在 招聘单里 生成新招聘单
                    recruitOrders.forEach(recruitOrder1 -> {
                        //取导致缺岗人不在招聘单里的
                        empList.forEach(emp ->{
                            recruitOrder1.getEmployeeSets().forEach(employee -> {
                                if(emp!=employee){
                                    employeeSet.add(emp);
                                    recruitOrderList.add(recruitOrder);
                                }
                            });
                        });
                    });

                }else {//缺岗，没有招聘单
                    //生成招聘单
                    empList.forEach(employee -> {
                        employeeSet.add(employee);
                    });
                    recruitOrderList.add(recruitOrder);
                }

//                recruitOrderRepository.saveAndFlush(recruitOrder);
            }  else if (need_qty >=0 && !recruitOrders.isEmpty()) {//不缺岗，有招聘单
                //废除招聘单
                recruitOrders.forEach(rOrder -> {
                    rOrder.setState("cancel");
                    recruitOrderRepository.saveAndFlush(rOrder);
                });

            }
        });
        //批量生成
       saveRecruitOrderList(recruitOrderList);

    }
    //批量生成
    private void saveRecruitOrderList(List<RecruitOrder> recruitOrderList){
        recruitOrderList.forEach(recruitOrder ->{
            recruitOrderRepository.saveAndFlush(recruitOrder);
        });
    }

    //人员编制的查询 在岗人员
    public List findEmployeeState(SimpleRequest request){
        Map<String,Map<String,Object>> date = request.getMap();
        String key = request.get("key");
        Map<String,Object> map = date.get("data");
        Object branchId =  map.get("BRANCH_ID");
        Object workPostId =  map.get("WORK_POST_ID");
        Branch branch = branchService.findOne((String)branchId);
        WorkPost workPost = workPostService.findOne((String)workPostId);
        final List<Employee> employeeList = new ArrayList<>();
        if(key.equals("REAL_QTY")){//在职的
            employeeList.addAll(employeeRepository.findByWorkBranchAndPost(branch,workPost));
        } else if(key.equals("TRANSFER_IN_QTY")){//将调入的
            //将调入的
            List<TransferApplicationItem> itemInList = ItmRepository.findByBranchAfterAndWorkPostAfterAndIconExecute(branch,workPost,false);
            itemInList = itemInList.stream().filter(item ->
                    item.getTransferApplications().getHrTransferType().getId().equals("000102")
                            &&item.getTransferApplications().getState().equals("done")).collect(Collectors.toList());

            itemInList.forEach(item -> {
                employeeList.add(item.getTransferUid());
            });

        } else if(key.equals("TRANSFER_OUT_QTY")){//将调出
            //将调出的
            List<TransferApplicationItem> itemOutList = ItmRepository.findByBranchAndWorkPostAndIconExecute(branch,workPost,false);

            itemOutList = itemOutList.stream().filter(item ->
                    item.getTransferApplications().getHrTransferType().getId().equals("000102")
                            &&item.getTransferApplications().getState().equals("done")).collect(Collectors.toList());

            itemOutList.forEach(item -> {
                employeeList.add(item.getTransferUid());
            });

        } else if (key.equals("LEAVE_QTY")){ //预离职
            employeeList.addAll(employeeRepository.findByWorkBranchAndPost
                    (branch,workPost).stream()
                    .filter(employee -> employee.getQuitState() != null)
                    .filter(employee -> employee.getQuitState().getId().equals("000412"))
                    .collect(Collectors.toList()));
        } else if (key.equals("DELAY_QTY")){ //待入职
            List<ApplyJobOrder> applyJobOrders = applyJobOrderRepository.findByBranchIdAndWorkPostIdAndState(branch.getId(), workPost.getId(), "firstTrial");
            applyJobOrders.forEach(applyJobOrder -> {
                employeeList.add(applyJobOrder.getEmployee());
            });
        } else if (key.equals("SPECIAL_QTY")){ //机电技工1和2
            employeeList.addAll(employeeRepository.findByWorkBranchAndJobAndRank(branch.getId(),"0004","004","005"));
        } else if (key.equals("WAITING_QTY")){ //待岗
            employeeList.addAll(employeeRepository.findByWorkBranchAndPostAndOnDutyState(Arrays.asList("000118"),branch.getId(),workPost.getId()));
        } else if (key.equals("HOLIDAYS_QTY")){ //长假
            employeeList.addAll(employeeRepository.findByWorkBranchAndPostAndOnDutyState(Arrays.asList("000394"),branch.getId(),workPost.getId()));
        } else if (key.equals("TEMPORARY_WORKER_QTY")){ //临时工
            employeeList.addAll(employeeRepository.findByWorkBranchAndPostAndJob(branch.getId(),workPost.getId(),"0013"));
        } else if (key.equals("HOURLY_WORKER_QTY")){ //小时工
            employeeList.addAll(employeeRepository.findByWorkBranchAndPostAndJob(branch.getId(),workPost.getId(),"0014"));
        } else if (key.equals("ON_TRIAL_QTY")){ //试用人数
            employeeList.addAll(employeeRepository.findByWorkBranchAndPostAndOnDutyState(Arrays.asList("000116","001121"),branch.getId(),workPost.getId()));
        } else if (key.equals("INTERNSHIP_QTY")){ //实习生
            employeeList.addAll(employeeRepository.findByWorkBranchAndPostAndOnDutyState(Arrays.asList("000119","000484","000418"),branch.getId(),workPost.getId()));
        }
        else {
           return new ArrayList();
        }
        return employeeList;
    }



}
